package org.polyforms.repository.jpa;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Query;

import org.apache.commons.lang.StringUtils;
import org.polyforms.repository.spi.QueryParameterResolver;

/**
 * Implementation of {@link QueryParameterResolver} for JPA 2.0.
 * 
 * @author Kuisong Tong
 * @since 1.0
 */
public final class Jpa2QueryParameterResolver implements QueryParameterResolver {
    /**
     * {@inheritDoc}
     */
    public Parameter[] getNamedParameters(final Query query) {
        final Set<javax.persistence.Parameter<?>> jpaParameters = query.getParameters();
        final Set<Parameter> parameters = new HashSet<Parameter>();
        for (final javax.persistence.Parameter<?> jpaParameter : jpaParameters) {
            final String name = jpaParameter.getName();
            if (name != null && !StringUtils.isNumeric(name)) {
                parameters.add(new JpaParameter(jpaParameter));
            }
        }
        return parameters.toArray(new Parameter[parameters.size()]);
    }

    private static final class JpaParameter implements Parameter {
        private final javax.persistence.Parameter<?> jpaParameter;

        /**
         * Create an adapter of JAP {@link javax.persistence.Parameter}.
         */
        public JpaParameter(final javax.persistence.Parameter<?> jpaParameter) {
            this.jpaParameter = jpaParameter;
        }

        /**
         * {@inheritDoc}
         */
        public String name() {
            return jpaParameter.getName();
        }
    }
}
